<template>
  <div class="new-friend">
    <div style="padding: 10px 0">
      <el-select v-model="filterWeChatId" size="small" clearable placeholder="所有微信">
        <el-option
          v-for="(wechat, index) in wechatsOnline"
          :key="index"
          :label="wechat.WeChatNick"
          :value="wechat.WeChatId"
          :disabled="!wechat.IsOnline"
        ></el-option>
      </el-select>
      <el-button style="margin-left: 10px" size="small" type="primary" @click="getNewFriends">刷新</el-button>
    </div>
    <!-- <p class="table-title">好友请求列表</p> -->
    <!-- 数据展示 -->
    <!-- <el-table :data="tableData[currentPage - 1]" stripe border height="60" class="table-data"> -->
    <el-table :data="newFriendsData" stripe border ref="table" :key="tableKey">
      <el-table-column label="所属微信" prop="WeChatId">
        <template slot-scope="{ row }">
          <span v-text="wechatsNameMap[row.WeChatId] || scope.WeChatId"></span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" prop="FriendNick"></el-table-column>
      <el-table-column label="头像" width="50px">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.Avatar">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="Gender" width="50px" label="性别" :formatter="formatGender"></el-table-column>
      <el-table-column label="来源">
        <template slot-scope="scope">
          <div v-if="scope.row.Source" v-text="$options.filters.getFriendSource(scope.row.Source)"></div>
        </template>
      </el-table-column>
      <el-table-column label="地区">
        <template slot-scope="scope">
          <p>{{ scope.row.Province }}</p>
          <p>{{ scope.row.City }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="Reason" label="验证信息"></el-table-column>
      <el-table-column label="时间">
        <template slot-scope="scope">
          <span v-text="$options.filters.timeFilter(scope.row.ReqTime)"></span>
        </template>
      </el-table-column>
      <el-table-column label="已加好友">
        <template slot-scope="scope">
          <div :style="scope.row.friends?'color:#c33;':''">
            <div v-for = "item in scope.row.friends">
            {{item.c_name}} | {{item.w_name}}
          </div>
          </div>

        </template>
      </el-table-column>
      <el-table-column prop="address" width="90px" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.State === 1" type="info" size="mini">已添加</el-button>
          <el-button v-else-if="timeNow - scope.row.ReqTime >= 24 * 60 * 60 * 1000 * 3" type="info" size="mini">
            已过期
          </el-button>
          <div v-else-if="!scope.row.black || (scope.row.black && scope.row.black.length==0)">
            <div style="margin-bottom:5px" v-if="scope.row.friends && scope.row.friends.length>0">
              <el-button size="mini" type="worring" @click="lahei(scope.$index, scope.row)">拉黑</el-button>
            </div>
            <div>
              <el-button size="mini" type="primary" @click="acceptRequest(scope.$index, scope.row)">接受</el-button>
            </div>
          </div>
          <div v-else>
            已拉黑
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <!-- <el-pagination
      style="margin: 10px auto"
      :current-page="currentPage"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="newFriends.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { AcceptFriendAddRequestTask, PullFriendAddReqListTask } from '@/api/webSocketApi'
import { getWechatFriendList, getBlack ,addBlack } from '@/api/admin/custom'

export default {
  name: 'ToolsNewFriend',
  data() {
    return {
      currentPage: 1,
      pageSize: 20,
      filterWeChatId: '',
      timeNow: new Date().getTime(),
      finds:[],
      tableKey:0,
      // newFriendsData: [] // 表格数据源
    }
  },
  computed: {
    ...mapGetters({
      wechatsOnline: 'conversation/wechatsOnline',
      wechatsNameMap: 'conversation/wechatsNameMap',
      newFriends: 'tools/newFriendsList',
      loginInfo:'loginInfo'
    }),
    newFriendsData() {
      // // 分页 每页50
      // const newFriendsPage = []
      // const size = this.pageSize
      // for (let i = 0; i < this.newFriends.length; i += size) {
      //   newFriendsPage.push(this.newFriends.slice(i, i + size))
      // }
      return this.newFriends
    }
  },
  created() {
    this.getNewFriends()
  },
  mounted() {
  },
  //监听newFriends
  watch: {
    newFriends() {
      this.$nextTick(() => {
        this.tableKey=this.tableKey+1;
      });
    }
  },
  methods: {
    // 获取新的朋友圈列表
    getNewFriends() {
            // 清空旧数据
      this.$store.commit('tools/RESET_NEW_FRIENDS_LIST')
      const st = new Date().getTime() - 4 * 24 * 3600 * 1000
      if (this.filterWeChatId) {
        PullFriendAddReqListTask(this.filterWeChatId, st, false, false)
      } else {
        for (const wechat of this.wechatsOnline) {
          PullFriendAddReqListTask(wechat.WeChatId, st, false, false)
        }
      }
    },
    async processNewFriendsData() {
      this.newFriendsData = []
      // 复制原始数据
    //   let newFriends=[{
    //     "FriendId": "wxid_1cvhx7ga8beh12",
    //     "FriendNo": "Arssine",
    //     "FriendNick": "東-",
    //     "Avatar": "http://wx.qlogo.cn/mmhead/ver_1/oIoZC8GudOHwY4iadjqRM10efptGWic3woN69FJnGGLDaAmYWvtz8V6rOQeTMo3ajx5T72ACeKIeo5mZzyXcBoCmEDyXrQw7yVKufOHlFpxkqLyWu5NKdjBLTXIe7Ss7nN/132",
    //     "Reason": "我是東-",
    //     "Gender": "Male",
    //     "Source": 6,
    //     "ReqTime": "1750316084000",
    //     "FirstReq": "1750316084000",
    //     "WeChatId": "wxid_ozk70jz9xrz619"
    // },{
    //     "FriendId": "wxid_1cvhx7ga8beh22",
    //     "FriendNo": "Arssine",
    //     "FriendNick": "東-",
    //     "Avatar": "http://wx.qlogo.cn/mmhead/ver_1/oIoZC8GudOHwY4iadjqRM10efptGWic3woN69FJnGGLDaAmYWvtz8V6rOQeTMo3ajx5T72ACeKIeo5mZzyXcBoCmEDyXrQw7yVKufOHlFpxkqLyWu5NKdjBLTXIe7Ss7nN/132",
    //     "Reason": "我是東-",
    //     "Gender": "Male",
    //     "Source": 6,
    //     "ReqTime": "1750316084000",
    //     "FirstReq": "1750316084000",
    //     "WeChatId": "wxid_ozk70jz9xrz619"
    // }];
      // const tempData = [...newFriends]
      const tempData = [...this.newFriends];
      
      // 并行获取每个好友的friends信息
      const tasks = tempData.map(async (item) => {
        try {
          // 先添加数据，显示加载中状态
          const newItem = { ...item, friends: '加载中...' }
          this.newFriendsData.push(newItem)
          
          // 获取friends信息
          const res = await getWechatFriendList(item.FriendId)
          // 更新数据
          const index = this.newFriendsData.findIndex(i => i.FriendId === item.FriendId)
          if (index !== -1) {
            this.$set(this.newFriendsData, index, { ...this.newFriendsData[index], friends: res.data })
          }
          const blk = await getBlack(item.FriendId)
          if (index !== -1) {
            this.$set(this.newFriendsData, index, { ...this.newFriendsData[index], black: blk.data })
          }
        } catch (error) {
          console.error('获取好友信息失败', error)
          // 更新为加载失败状态
          const index = this.newFriendsData.findIndex(i => i.FriendId === item.FriendId)
          if (index !== -1) {
            this.$set(this.newFriendsData, index, { ...this.newFriendsData[index], friends: '加载失败' })
          }
        }
      })
      
      // 等待所有任务完成
      await Promise.allSettled(tasks)
    },
    // 格式化性别
    formatGender(row) {
      if (row.Gender === 'Male') {
        return '男'
      } else if (row.Gender === 'Female') {
        return '女'
      } else {
        return '未知'
      }
    },
    // handleSizeChange(val) {
    //   this.pageSize = val
    // },
    // handleCurrentChange(val) {
    //   this.currentPage = val
    // },
    // 接受请求
    acceptRequest(rowIndex, row) {
      this.$prompt('设置备注(非必需)', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{0,50}$/,
        inputErrorMessage: '备注超过50个字符'
      })
        .then(({ value }) => {
          row.State = 1
          AcceptFriendAddRequestTask(row.WeChatId, row.FriendId, 1, value)
          this.$store.commit('tools/UPDATE_ACCEPTE_STATE', { ri: rowIndex, rd: row })
          this.getNewFriends();
        })
        .catch(() => {})
    },
    lahei(rowIndex, row) {
      this.$prompt('设置备注(非必需)', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{0,50}$/,
        inputErrorMessage: '备注超过50个字符'
      })
        .then(({ value }) => {
          /**
           *     private Integer id;
    private String wx_id;
    private String wx_name;
    private Integer is_deleted;
    private Date create_time;
    private int create_account;
    private String remark;
           */
          let data={
            wx_id:row.FriendId,
            wx_name:row.FriendNick,
            create_account:this.loginInfo.name,
            remark:value
          }
          addBlack(data).then((res) => {
            this.getNewFriends();
          });
        })
        .catch(() => {})
    }
    //判斷是否已經添加了好友
  }
}
</script>

<style lang="scss" scoped>
.new-friend {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  padding: 0 20px 10px 20px;
  overflow: hidden;

  // .table-title {
  //   color: #999999;
  //   height: 30px;
  //   line-height: 30px;
  //   font-size: 14px;
  // }

  // ::v-deep .table-data {
  //   flex: 1 1 auto;
  //   .friend-nick {
  //     display: flex;
  //     align-items: center;
  //   }
  // }
}
</style>
